import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: {
      id: null,
      username: '',
      email: '',
      phone: '',
      avatar: '',
      createdAt: '',
      bio: ''
    },
    // 登录状态
    isLoggedIn: false,
    // 地址列表
    addresses: [],
    // 订单列表
    orders: [],
    // 会员信息
    membership: {
      status: 'inactive', // active, inactive
      level: '普通会员', // 普通会员, 银卡会员, 金卡会员, 钻石会员
      expireDate: null,
      totalSpend: 0,
      points: 0
    },
    // 登录监听器数组
    _loginListeners: []
  }),
  
  getters: {
    // 获取默认地址
    defaultAddress: (state) => {
      return state.addresses.find(addr => addr.isDefault) || state.addresses[0] || null
    },
    // 获取待处理订单
    pendingOrders: (state) => {
      return state.orders.filter(order => order.status === 'pending')
    }
  },
  
  actions: {
    // 登录
    login(credentials) {
      // 模拟登录验证
      console.log('登录凭证:', credentials)
      
      // 这里应该是实际的API调用，现在使用模拟数据
      return new Promise((resolve) => {
        setTimeout(() => {
          this.isLoggedIn = true
          this.userInfo = {
            id: '1',
            username: credentials.username,
            email: 'example@mail.com',
            phone: '13800138000',
            avatar: '',
            createdAt: '2024-01-01',
            bio: ''
          }
          // 模拟会员数据
          this.membership = {
            status: 'inactive',
            level: '普通会员',
            expireDate: null,
            totalSpend: 1250, // 模拟已消费金额
            points: 125
          }
          // 保存到本地存储
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          localStorage.setItem('isLoggedIn', 'true')
          localStorage.setItem('membership', JSON.stringify(this.membership))
          
          // 触发登录成功监听器
          this._triggerLoginListeners(true, this.userInfo)
          
          resolve({ success: true })
        }, 500)
      })
    },
    
    // 注册
    register(userData) {
      // 模拟注册过程
      console.log('注册数据:', userData)
      
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true })
        }, 500)
      })
    },
    
    // 登出
    logout() {
      const wasLoggedIn = this.isLoggedIn
      this.isLoggedIn = false
      this.userInfo = {
        id: null,
        username: '',
        email: '',
        phone: '',
        avatar: '',
        createdAt: '',
        bio: ''
      }
      this.addresses = []
      this.orders = []
      this.membership = {
        status: 'inactive',
        level: '普通会员',
        expireDate: null,
        totalSpend: 0,
        points: 0
      }
      // 清除本地存储
      localStorage.removeItem('userInfo')
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('membership')
      
      // 如果之前是登录状态，则触发登出监听器
      if (wasLoggedIn) {
        this._triggerLoginListeners(false, null)
      }
    },
    
    // 更新用户信息
    updateProfile(profileData) {
      console.log('更新个人信息:', profileData)
      
      return new Promise((resolve) => {
        setTimeout(() => {
          this.userInfo = { ...this.userInfo, ...profileData }
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          resolve({ success: true })
        }, 500)
      })
    },
    
    // 获取地址列表
    fetchAddresses() {
      // 模拟获取地址数据
      return new Promise((resolve) => {
        setTimeout(() => {
          this.addresses = [
            {
              id: '1',
              name: '张三',
              phone: '13800138000',
              province: '上海市',
              city: '上海市',
              district: '浦东新区',
              detail: '张江高科技园区博云路2号',
              isDefault: true
            },
            {
              id: '2',
              name: '张三',
              phone: '13800138000',
              province: '北京市',
              city: '北京市',
              district: '朝阳区',
              detail: '建国路88号',
              isDefault: false
            }
          ]
          resolve(this.addresses)
        }, 500)
      })
    },
    
    // 添加地址
    addAddress(addressData) {
      console.log('添加新地址:', addressData)
      
      return new Promise((resolve) => {
        setTimeout(() => {
          const newAddress = {
            id: Date.now().toString(),
            ...addressData
          }
          this.addresses.push(newAddress)
          resolve({ success: true })
        }, 500)
      })
    },
    
    // 更新地址
    updateAddress(addressId, addressData) {
      console.log('更新地址:', addressId, addressData)
      
      return new Promise((resolve) => {
        setTimeout(() => {
          const index = this.addresses.findIndex(addr => addr.id === addressId)
          if (index !== -1) {
            this.addresses[index] = { ...this.addresses[index], ...addressData }
            resolve({ success: true })
          } else {
            resolve({ success: false, message: '地址不存在' })
          }
        }, 500)
      })
    },
    
    // 删除地址
    deleteAddress(addressId) {
      console.log('删除地址:', addressId)
      
      return new Promise((resolve) => {
        setTimeout(() => {
          this.addresses = this.addresses.filter(addr => addr.id !== addressId)
          resolve({ success: true })
        }, 500)
      })
    },
    
    // 设置默认地址
    setDefaultAddress(addressId) {
      console.log('设置默认地址:', addressId)
      
      return new Promise((resolve) => {
        setTimeout(() => {
          this.addresses.forEach(addr => {
            addr.isDefault = addr.id === addressId
          })
          resolve({ success: true })
        }, 500)
      })
    },
    
    // 获取订单列表
    fetchOrders() {
      // 模拟获取订单数据
      return new Promise((resolve) => {
        setTimeout(() => {
          this.orders = [
            {
              id: 'ORD-20240601-001',
              date: '2024-06-01',
              totalAmount: 299.00,
              status: 'completed',
              items: [
                { id: '1', name: '产品A', quantity: 1, price: 299.00 }
              ]
            },
            {
              id: 'ORD-20240520-001',
              date: '2024-05-20',
              totalAmount: 599.00,
              status: 'pending',
              items: [
                { id: '2', name: '产品B', quantity: 2, price: 299.50 }
              ]
            },
            {
              id: 'ORD-20240501-001',
              date: '2024-05-01',
              totalAmount: 199.00,
              status: 'completed',
              items: [
                { id: '3', name: '产品C', quantity: 1, price: 199.00 }
              ]
            }
          ]
          resolve(this.orders)
        }, 500)
      })
    },
    
    // 从本地存储加载用户状态
    loadFromLocalStorage() {
      const userInfo = localStorage.getItem('userInfo')
      const isLoggedIn = localStorage.getItem('isLoggedIn')
      const membership = localStorage.getItem('membership')
      
      if (userInfo && isLoggedIn === 'true') {
        try {
          this.userInfo = JSON.parse(userInfo)
          this.isLoggedIn = true
          
          // 加载会员数据
          if (membership) {
            this.membership = JSON.parse(membership)
            // 检查会员是否过期
            this._checkMembershipExpiry()
          }
          
          // 自动获取地址和订单数据
          this.fetchAddresses()
          this.fetchOrders()
          
          // 触发登录成功监听器
          this._triggerLoginListeners(true, this.userInfo)
        } catch (error) {
          console.error('加载用户数据失败:', error)
          this.logout()
        }
      }
    },
    
    // 检查会员是否过期
    _checkMembershipExpiry() {
      if (this.membership.status === 'active' && this.membership.expireDate) {
        const now = new Date()
        const expireDate = new Date(this.membership.expireDate)
        if (now > expireDate) {
          // 会员已过期
          this.membership.status = 'inactive'
          this.membership.level = '普通会员'
          this.membership.expireDate = null
          // 更新本地存储
          localStorage.setItem('membership', JSON.stringify(this.membership))
        }
      }
    },
    
    // 升级会员
    upgradeMembership(plan) {
      console.log('升级会员:', plan)
      
      return new Promise((resolve) => {
        setTimeout(() => {
          const now = new Date()
          let expireDate
          
          switch (plan) {
            case 'monthly':
              expireDate = new Date(now.setMonth(now.getMonth() + 1))
              break
            case 'yearly':
              expireDate = new Date(now.setFullYear(now.getFullYear() + 1))
              break
            case 'lifetime':
              // 终身会员设置为100年后过期
              expireDate = new Date(now.setFullYear(now.getFullYear() + 100))
              break
          }
          
          this.membership = {
            status: 'active',
            level: '金卡会员', // 开通会员直接升级为金卡
            expireDate: expireDate.toISOString(),
            totalSpend: this.membership.totalSpend,
            points: this.membership.points
          }
          
          // 保存到本地存储
          localStorage.setItem('membership', JSON.stringify(this.membership))
          
          resolve({ success: true })
        }, 800)
      })
    },
    
    // 续费会员
    renewMembership(plan) {
      console.log('续费会员:', plan)
      
      return new Promise((resolve) => {
        setTimeout(() => {
          let currentExpireDate = this.membership.expireDate ? new Date(this.membership.expireDate) : new Date()
          const now = new Date()
          
          // 如果当前日期已经超过过期日期，从今天开始计算
          if (now > currentExpireDate) {
            currentExpireDate = now
          }
          
          switch (plan) {
            case 'monthly':
              currentExpireDate.setMonth(currentExpireDate.getMonth() + 1)
              break
            case 'yearly':
              currentExpireDate.setFullYear(currentExpireDate.getFullYear() + 1)
              break
          }
          
          this.membership.expireDate = currentExpireDate.toISOString()
          this.membership.status = 'active'
          
          // 保存到本地存储
          localStorage.setItem('membership', JSON.stringify(this.membership))
          
          resolve({ success: true })
        }, 800)
      })
    },
    
    // 更新会员等级（根据消费金额）
    updateMembershipLevel(totalSpend) {
      this.membership.totalSpend = totalSpend
      
      if (totalSpend >= 20000) {
        this.membership.level = '钻石会员'
      } else if (totalSpend >= 5000) {
        this.membership.level = '金卡会员'
      } else if (totalSpend >= 1000) {
        this.membership.level = '银卡会员'
      } else {
        this.membership.level = '普通会员'
      }
      
      // 保存到本地存储
      localStorage.setItem('membership', JSON.stringify(this.membership))
    },
    
    // 添加积分
    addPoints(points) {
      this.membership.points += points
      localStorage.setItem('membership', JSON.stringify(this.membership))
    },
    
    // 使用积分
    usePoints(points) {
      if (points <= this.membership.points) {
        this.membership.points -= points
        localStorage.setItem('membership', JSON.stringify(this.membership))
        return true
      }
      return false
    },
    
    // 添加登录状态监听器
    addLoginListener(callback) {
      if (typeof callback === 'function' && !this._loginListeners.includes(callback)) {
        this._loginListeners.push(callback)
        // 立即执行一次回调，提供当前状态
        callback(this.isLoggedIn, this.isLoggedIn ? this.userInfo : null)
      }
    },
    
    // 移除登录状态监听器
    removeLoginListener(callback) {
      const index = this._loginListeners.indexOf(callback)
      if (index !== -1) {
        this._loginListeners.splice(index, 1)
      }
    },
    
    // 触发所有登录状态监听器
    _triggerLoginListeners(isLoggedIn, userInfo) {
      console.log('触发登录状态监听器:', isLoggedIn ? '登录成功' : '登出')
      this._loginListeners.forEach(callback => {
        try {
          callback(isLoggedIn, userInfo)
        } catch (error) {
          console.error('登录监听器执行出错:', error)
        }
      })
    }
  }
})